<template>
    <v-container>
        <Breadcrumb>
            <SecondFunc 
            :title="title"
            :formConfig="formConfig"
            :initialData="initialData"
            @optSave="saveData"
            />
        </Breadcrumb>

        <dynamic-table
            :title="title"
            :data="data"
            :columns="columns"
            @optEdit="editData"
            @optDel="delData"
            @optSave="saveData"
        />
    </v-container>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { getApiList,deleteApi, createApi, updateApi, queryApi, getGroupList } from '@/api';
import DynamicTable from '@/components/common/dynamicTable/index.vue';
import Breadcrumb from '@/components/common/breadcrumb/index.vue';
import SecondFunc from '@/components/common/secondFunc/index.vue';
import { changeIsShowCreateButton, changeIsEdit, changeCommonId,changeCurLabel } from '@/assets/js/common';
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex';


// api管理页面
// 1. 默认展示api接口列表 
//      * 需要给表组件传递字段参数 columns tableData
// 2. 如果需要新增数据，在点击创建时，传递创建相关的数据 
//      * 需要传递按钮相关、新增页面 label 相关的参数 title btnData formData
// 3. 如果需要对已有数据编辑，点击编辑按钮时，在列表组件中传递数据 
//      * 需要传递 label, formData


let title = ref('api')
let store = useStore()
let data = ref([])
let columns = ref([
    { prop: 'id', label: 'ID', width: "100", sortable: true, fixed: "fixed" },
    { prop: 'name', label: '名称', width: "200",fixed: "fixed" },
    { prop: 'method', label: '方法', width: "100" },
    { prop: 'path', label: '路径', width: "300", sortable: true },
    { prop: 'project', label: '项目', width: "120" },
    { prop: 'group', label: '分组', width: "120" },
    { prop: 'desc', label: '描述', width: "200" },
    { prop: 'create_time', label: '创建时间', width: "180" },
    { prop: 'update_time', label: '更新时间', width: "180" },
    { prop: 'state', label: '状态', width: "200" },
])
let formConfig = ref([
                {
                    label: '名称',
                    name: 'name',
                    ktype: 'input',
                    styleSet: '',
                    required: true,
                },
                {
                    label: '方法',
                    name: 'method',
                    ktype: 'select',
                    options: [
                        {label: "GET", value: "GET"},
                        {label: "POST", value: "POST"},
                        {label: "PUT", value: "PUT"},
                        {label: "DELETE", value: "DELETE"},
                        {label: "PATCH", value: "PATCH"},
                        {label: "HEAD", value: "HEAD"},
                        {label: "OPTIONS", value: "OPTIONS"},
                    ],
                    styleSet: '',
                    required: true,
                },
                {
                    label: '请求头',
                    name: 'headers',
                    ktype: 'input',
                    styleSet: '',
                    required: false,
                },
                {
                    label: '路径',
                    name: 'path',
                    ktype: 'input',
                    styleSet: '',
                    required: true,
                },
                {
                    label: '分组',
                    name: 'group',
                    ktype: 'select',
                    options: [],
                    styleSet: ''
                },
                {
                    label: '项目',
                    name: 'project',
                    ktype: 'input',
                    styleSet: ''
                },
                {
                    label: '请求体',
                    name: 'content',
                    ktype: 'textarea',
                    styleSet: ''
                },
                {
                    label: '描述',
                    name: 'desc',
                    ktype: 'input',
                    styleSet: ''
                },
                {
                    label: '版本',
                    name: 'version',
                    ktype: 'input',
                    styleSet: ''
                },
                {
                    label: '状态',
                    name: 'state',
                    ktype: 'switch',
                    styleSet: ''
                }
])
let initialData = ref({})


onMounted(() => {
    changeCurLabel("接口管理")
    changeIsShowCreateButton(true)
    queryList()
    initGroupOptions()
    
})

onBeforeUnmount(() => {
    changeCommonId(0)
})

function queryList(){
    try {
        getApiList().then((res)=>{
            data.value = res.data
        })
    } catch (error) {
        console.error('Error querying api list:', error)
    }
}

function editData(id){
    try {
        changeCommonId(id)
        console.log("来自子组件的消息,要编辑数据ID是: ", id)
        queryApi({id: id}).then(resp => {
            let res = resp.data
            if ( res ) {
                for (var i=0; i<Object.keys(res).length; i++) {
                    initialData.value[Object.keys(res)[i]] = res[Object.keys(res)[i]]
                }
            }
        })
    } catch (error) {
        console.error("Fetch api data error:", error)
    }
}

function saveData(saveData){
    if (store.getters.getIsEdit){
        updateApi(saveData).then(()=>{
            ElMessage({
                title: "Update " + title.value,
                type: "primary",
                message: '更新成功'
            })
        })
    } else {
        createApi(saveData).then(()=>{
            ElMessage({
                title: "Create " + title.value,
                type: "success",
                message: '创建成功'
            })
        })
    }
    queryList()
}

function delData(id){
    if (confirm('确定要删除这个记录么吗？')){
        try {
            deleteApi({id: id}).then(()=>{
                queryList()
                ElMessage({
                    title: "Delete " + title.value,
                    type: "warning",
                    message: '删除成功'
                })
            })
        } catch (error) {
            console.error('Error deleting api:', error)
        }
    } 
}

function initGroupOptions(){
    // let { options } = useOptions()
    // 初始化分组选项
    // for (var i=0;i<formData.value.length;i++){
    //     if (formConfig.value[i]["name"] == 'group'){
    //         formConfig.value[i]['options'] = options.value
    //     }
    // }
}

</script>